#!/bin/sh

#wget https://github.com/fatedier/frp/releases/download/v0.38.0/frp_0.38.0_linux_amd64.tar.gz

server_port=7022
http_port=7080

sh_path=$(
    cd $(dirname $0)
    pwd
)

usage() {
    cat <<-EOF
Usage:
  ${0##*/} [flags]
Flags:
    -P,     int bind_port (default 7022)
    -H,     int vhost_https_port (default 7080)
    -y,         assume yes
EOF
}

while getopts ":hyH:P:" opt; do
    case $opt in
    H)
        http_port=$OPTARG
        ;;
    P)
        server_port=$OPTARG
        ;;
    y)
        ok="y"
        ;;
    h)
        usage
        exit 0
        ;;
    \?)
        echo "Invalid option: -${OPTARG}"
        usage
        exit 1
        ;;
    esac
done

if [ ! -n "$ok" ]; then
    read -p "是否初始化[y/n]" ok
fi

if [ "$ok" = "y" ]; then
    systemctl stop frps && systemctl disable frps
    cat >frps.ini <<-EOF
[common]
bind_port = $server_port
vhost_http_port = $http_port
EOF

    cat >systemd/frps.service <<-EOF
[Unit]
Description=Frp Server Service
After=network.target

[Service]
Type=simple
User=$(whoami)
Restart=on-failure
RestartSec=5s
ExecStart=/usr/bin/frps -c /etc/frp/frps.ini
LimitNOFILE=1048576

[Install]
WantedBy=multi-user.target
EOF

    echo '生成对应客户端配置 frpc.ini'

    cat >frpc.ini <<-EOF
[common]
server_addr = $(curl ifconfig.me)
server_port = $server_port

[ssh]
type = tcp
local_ip = 127.0.0.1
local_port = 22
;ssh username@ip -p 7443
remote_port = 7443

[VSCode Live Server]
type = tcp
local_ip = 127.0.0.1
local_port = 5500
;http://ip:8848
remote_port = 8848
EOF

fi

echo '创建frps.service链接'

ln -sf $sh_path'/systemd/frps.service' /lib/systemd/system/frps.service

echo '创建frps.ini配置链接'
if [ ! -d /etc/frp ]; then
    mkdir /etc/frp
fi
ln -sf $sh_path'/frps.ini' /etc/frp/frps.ini

echo '创建frps可执行程序链接'
chmod +x frps
ln -sf $sh_path'/frps' /usr/bin/frps

echo 'frps服务加入开机自启'
systemctl enable frps
systemctl start frps
systemctl status frps
